<?php

namespace Home\Controller;

use Home\Tool\History;

class ExplorerController extends BaseController
{

    private $path = '';

    public function __construct(){
        parent::__construct();

        $path = I('path');
        if ($path) {
            $this->path = _DIR($path);
        }
    }

    public function index()
    {
        if($this->path !=''){
            $dir = _DIR_CLEAR($this->path);
        }else if(session('this_path')){
            $dir = _DIR_CLEAR(session('this_path'));
        }else{
            $dir = '/';//首次进入系统,不带参数
            if ($GLOBALS['is_root']) {
                $dir = WEB_ROOT;
            }
        }
        $dir = rtrim($dir,'/').'/';
        $this->assign('dir',$dir);

        $this->display('index');
    }

    public function pathList()
    {
        $session = session('history') ? session('history') : false;
        $user_path = I('path');
        $user_type = I('type');
        if (is_array($session)) {
            $history = new History($session);
            if ($user_path == "") {
                $user_path = $history->getFirst();
            } else {
                $history->add($user_path);
                session('history', $history->getHistory());
            }
        } else {
            $history = new History(array(), 20);
            if ($user_path == "") $user_path = '/';
            $history->add($user_path);
            session('history', $history->getHistory());
        }

        //回收站不记录前进后退
        if ($user_path != '*recycle*/' && (!$user_type || $user_type !== 'desktop')) {
            session('this_path', $user_path);
        }
        $list = $this->path($this->path);
        $list['history_status'] = array('back' => $history->isback(), 'next' => $history->isnext());
        $this->ajaxReturn($list);
    }

    public function treeList()
    {//树结构
        $app = I('app');//是否获取文件 传folder|file
        $type = I('type');
        $this_path = I('this_path');
        $path = I('path');
        $name = I('name');
        if ($type == 'init') {
            $this->_tree_init($app);
        }
        if ($this_path) {
            $path = _DIR($this_path);
        } else {
            $path = _DIR($path . $name);
        }
        if (!is_readable($path)) {
            show_json($path, false);
        }
        $list_file = ($app == 'editor' ? true : false);//编辑器内列出文件
        $list = $this->path($path, $list_file, true);
        function sort_by_key($a, $b)
        {
            if ($a['name'] == $b['name']) return 0;
            return ($a['name'] > $b['name']) ? 1 : -1;
        }

        usort($list['folderlist'], "sort_by_key");
        usort($list['filelist'], "sort_by_key");
        if ($app == 'editor') {
            $res = array_merge($list['folderlist'], $list['filelist']);
            show_json($res, true);
        } else {
            show_json($list['folderlist'], true);
        }
    }
}